package Communication;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Socket;
import java.net.URL;

import org.apache.http.client.HttpClient;

import android.util.Log;

public class Communication {
	
	public Communication(File file, String fileName)
	{
		
	}
	
	public static int sendImage(File file, String fileName)
	{
		try{
			Log.d("COMMUNICATION", "Connecting to socket..");
			Socket socket = new Socket("195.240.141.198", 2235);

			byte [] byteArray = new byte[(int)file.length()];
			
			Log.d("FILE", file.toString());
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream bis = new BufferedInputStream(fis);
			bis.read(byteArray,0, byteArray.length);
			OutputStream os = socket.getOutputStream();
			OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
			out.write("" + file.length() + "\n");
			out.write(fileName);
			out.flush();
			Log.d("COMMUNICATION", "Sending data..");
			os.write(byteArray, 0, byteArray.length);
			os.flush();

			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String decodedString = in.readLine();
			//while ((decodedString = in.readLine()) != null) {
			//	Log.d("COMMUNICATION", decodedString);
			//}
			
			in.close();
			os.close();
			
			socket.close();
			Log.d("COMMUNICATION", decodedString);
			if (decodedString.startsWith("OK!"))
				return 1;
			else
				return 0;
		}
		catch (Exception e)
		{
			Log.e("ERROR", e.getMessage());
			return 0;
		}
	}
}

